import 'package:date_format/date_format.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app/commom/Dio.dart';
import 'package:flutter_app/commom/Global.dart';
import 'package:percent_indicator/percent_indicator.dart';

import 'package:folding_cell/folding_cell.dart';


import 'AplResultCard.dart';
import 'HYSizeFit.dart';
import 'ReleasePjResultCard.dart';

class UndertakeItems extends StatefulWidget {
  UndertakeItems({
    Key key,
  }) : super(key: key);
  @override
  State<StatefulWidget> createState() {
    return UndertakeItemsState();
  }
}

class UndertakeItemsState extends State<UndertakeItems> {
  double mCurrentValue = 0.0;
  //final _foldingCellKey1 = GlobalKey<SimpleFoldingCellState>();
  _showBottomSheet(BuildContext context, int position) {
    return showModalBottomSheet(
        context: context,
        builder: (BuildContext bc) {
          return Stack(
            children: <Widget>[
              Container(
                height: HYSizeFit.setPx(180),
                width: double.infinity,
                color: Colors.black54,
              ),
              Container(
                  height: HYSizeFit.setPx(180),
                  //margin: EdgeInsets.only(right: HYSizeFit.setPx(20), left: HYSizeFit.setPx(20)),
                  decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.only(
                        topLeft: Radius.circular(10),
                        topRight: Radius.circular(10),
                      )),
                  child: Container(
                      child: UpdateProgress(
                          pdId: Global.findUserProcedures.packageProcedures[position]['pdId'],
                          schedule: Global.findUserProcedures.packageProcedures[position]['pdSchedule'].toString()))),
            ],
          );
        });
  }

  @override
  void initState() {
    Global.findUserProcedures.packageProcedures.forEach((element) {
      element['pdSchedule'] == null ? element['pdSchedule'] = 0 : element['pdSchedule'];
      print(element['pdSchedule'].runtimeType);
      switch (element['pdStatus']) {
        case 401:
          {
            element['pdStatusTxt'] = '进行中';
          }
          break;
        case 402:
          {
            element['pdStatusTxt'] = '已完成';
          }
          break;
        default:
          {
            print("Invalid choice");
          }
          break;
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return MediaQuery.removePadding(
      child: Container(
        child: ListView.builder(
            padding: EdgeInsets.fromLTRB(0, 0, 0, 10),
            itemCount: (Global.findUserProcedures.packageProcedures == null)
                ? 0
                : Global.findUserProcedures.packageProcedures.length,
            //itemExtent: HYSizeFit.setPx(120),
            shrinkWrap: true,
            //列表项构造器
            itemBuilder:(context, index){
              return SimpleFoldingCell.create(
                frontWidget: _buildFrontWidget(index),
                innerWidget: _buildInnerWidget(index),
                cellSize: Size(MediaQuery.of(context).size.width, 110),
                padding: EdgeInsets.all(5),
                animationDuration: Duration(milliseconds: 300),
                borderRadius: 15,
              );
            }
        ),
      ),
      removeTop: true,
      context: context,
    );
  }
  Widget _buildFrontWidget(int position) {
    return Builder(
        builder: (BuildContext context){
          return Container(
            decoration: BoxDecoration(
              //border: Border.all(width: 2.0, color: Colors.blueGrey),
              borderRadius: BorderRadius.all(Radius.circular(.0)),
              color: Colors.white,
              boxShadow: [
                BoxShadow(
                  offset: Offset(1, 0),
                  blurRadius: 10,
                  spreadRadius: 15,
                  color: Color.fromARGB(20, 0, 0, 0),
                ),
              ],
            ),
            //color: Colors.white,
            child: Stack(
              children: [
                Padding(
                  padding: EdgeInsets.only(top: HYSizeFit.setPx(10), left: 5, bottom: HYSizeFit.setPx(5), right: 5),
                  child: Flex(
                    direction: Axis.horizontal,
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Flex(
                        direction: Axis.vertical,
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        //mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        //crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Row(
                            mainAxisAlignment:
                            MainAxisAlignment.spaceBetween,
                            crossAxisAlignment: CrossAxisAlignment.baseline,
                            children: [
                              Text(
                                Global.findUserProcedures.packageProcedures[position]['pdName'],
                                style: TextStyle(
                                    color: Colors.black54,
                                    fontSize: 23,
                                    fontWeight: FontWeight.bold),
                              ),
                              Padding(
                                  padding:
                                  EdgeInsets.only(left: 5, right: 5)),
                              Text(
                                "状态：" +
                                    Global.findUserProcedures
                                        .packageProcedures[position]
                                    ['pdStatusTxt'],
                                style: TextStyle(color: Colors.black54),
                              )
                            ],
                          ),
                          Padding(padding: EdgeInsets.only(top: 10)),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: [
                              Container(
                                child: OutlineButton(
                                    borderSide: BorderSide(
                                        color: Colors.black26, width: HYSizeFit.setPx(1)),
                                    shape: RoundedRectangleBorder(
                                        borderRadius: BorderRadius.circular(5)),
                                    child: Text(
                                      '更新进度',
                                      style: TextStyle(
                                          color: Colors.black87,
                                          fontSize: HYSizeFit.setPx(12)),
                                    ),
                                    onPressed: () {
                                      _showBottomSheet(context, position);
                                    }),
                              ),
                              Padding(padding: EdgeInsets.only(left: HYSizeFit.setPx(10))),
                              Container(
                                child: OutlineButton(
                                    borderSide: BorderSide(
                                        color: Colors.black26, width: HYSizeFit.setPx(1)),
                                    shape: RoundedRectangleBorder(
                                        borderRadius:
                                        BorderRadius.circular(5)),
                                    child: Text(
                                      '交工请求',
                                      style: TextStyle(
                                          color: Colors.black87,
                                          fontSize: HYSizeFit.setPx(12)),
                                    ),
                                    onPressed: () {
                                      _onApplyFinish(context, position);
                                    }),
                              ),
                            ],
                          ),
                        ],
                      ),
                      Padding(padding: EdgeInsets.only(left: HYSizeFit.setPx(10))),
                      Column(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                              Global.findUserProcedures.packageProcedures[position]['pdDemand'] != null ?
                              //"开始时间：" + Global.findUserProcedures.packageProcedures[position]['pdProtime']:
                              "数量：" + Global.findUserProcedures.packageProcedures[position]['pdDemand'].toString()
                                  : "未设置",
                              style: TextStyle(
                                color: Colors.black54,
                                fontSize: HYSizeFit.setPx(12),
                              )),
                          Text(
                              Global.findUserProcedures.packageProcedures[position]['pdProtime'] != null ?
                              "开始时间：" + formatDate(DateTime.parse(Global.findUserProcedures.packageProcedures[position]['pdProtime']), [yyyy, '-', mm, '-', dd]):
                              "未设置",
                              style: TextStyle(
                                color: Colors.black54,
                                fontSize: HYSizeFit.setPx(12),
                              )),
                          Text(
                              Global.findUserProcedures.packageProcedures[position]['pdDeltime'] != null?
                              "结束时间：" + formatDate(DateTime.parse(Global.findUserProcedures.packageProcedures[position]['pdDeltime']), [yyyy, '-', mm, '-', dd]):
                              "未设置",
                              style: TextStyle(
                                color: Colors.black54,
                                fontSize: HYSizeFit.setPx(12),
                              )),
                          Text(
                              Global.findUserProcedures.packageProcedures[position]['pdDemand'] != null ?
                              //"开始时间：" + Global.findUserProcedures.packageProcedures[position]['pdProtime']:
                              "所需业务：" +
                                  Global.findUserProcedures.packageProcedures[position]['pdDemand'].toString() : "未设置",
                              style: TextStyle(
                                color: Colors.black54,
                                fontSize: HYSizeFit.setPx(12),
                              )),
                        ],
                      ),
                    ],
                  ),
                ),
                Positioned(
                    top: HYSizeFit.setPx(-7),
                    right: 0,
                    child: GestureDetector(
                      child: Container(
                        height: HYSizeFit.setPx(20),
                        width: HYSizeFit.setPx(50),
                        decoration: new BoxDecoration(
                          //border: new Border.all(color: Colors.black12, width: 0.5), // 边色与边宽度
                          color: Colors.black12, // 底色
                          borderRadius:
                          BorderRadius.all(Radius.circular(7.0)), // 也可控件一边圆角大小
                          //borderRadius: new BorderRadius.vertical(top: Radius.elliptical(20, 60)),
                        ),
                        //color: Colors.black12,
                        child: Icon(
                          Icons.linear_scale_rounded,
                          size: HYSizeFit.setPx(30),
                          color: Colors.blueGrey,
                        ),
                      ),
                      onTap: () {
                        final foldingCellState = context
                            .findAncestorStateOfType<SimpleFoldingCellState>();
                        foldingCellState?.toggleFold();
                      },
                    ))
              ],
            ),
          );
    });
  }
  Widget _buildInnerWidget(int position) {
    return Builder(
        builder: (BuildContext context){
          return Container(
            decoration: BoxDecoration(
              //border: Border.all(width: 2.0, color: Colors.blueGrey),
              borderRadius: BorderRadius.all(Radius.circular(.0)),
              color: Colors.white,
              boxShadow: [
                BoxShadow(
                  offset: Offset(1, 0),
                  blurRadius: 10,
                  spreadRadius: 15,
                  color: Color.fromARGB(20, 0, 0, 0),
                ),
              ],
            ),
            //color: Colors.white,
            child: Stack(
              children: [
                Column(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Padding(
                      padding: EdgeInsets.only(top: HYSizeFit.setPx(10), left: 5, bottom: HYSizeFit.setPx(5), right: 5),
                      child: Flex(
                        direction: Axis.horizontal,
                        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Flex(
                            direction: Axis.vertical,
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            //mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            //crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Row(
                                mainAxisAlignment:
                                MainAxisAlignment.spaceBetween,
                                crossAxisAlignment: CrossAxisAlignment.baseline,
                                children: [
                                  Text(
                                    Global.findUserProcedures
                                        .packageProcedures[position]['pdName'],
                                    style: TextStyle(
                                        color: Colors.black54,
                                        fontSize: 23,
                                        fontWeight: FontWeight.bold),
                                  ),
                                  Padding(
                                      padding:
                                      EdgeInsets.only(left: 5, right: 5)),
                                  Text(
                                    "状态：" +
                                        Global.findUserProcedures
                                            .packageProcedures[position]
                                        ['pdStatusTxt'],
                                    style: TextStyle(color: Colors.black54),
                                  )
                                ],
                              ),
                              Padding(padding: EdgeInsets.only(top: 10)),
                              Row(
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                crossAxisAlignment: CrossAxisAlignment.center,
                                children: [
                                  Container(
                                    child: OutlineButton(
                                        borderSide: BorderSide(
                                            color: Colors.black26, width: HYSizeFit.setPx(1)),
                                        shape: RoundedRectangleBorder(
                                            borderRadius: BorderRadius.circular(5)),
                                        child: Text(
                                          '更新进度',
                                          style: TextStyle(
                                              color: Colors.black87,
                                              fontSize: HYSizeFit.setPx(12)),
                                        ),
                                        onPressed: () {
                                          _showBottomSheet(context, position);
                                        }),
                                  ),
                                  Padding(padding: EdgeInsets.only(left: HYSizeFit.setPx(10))),
                                  Container(
                                    child: OutlineButton(
                                        borderSide: BorderSide(
                                            color: Colors.black26, width: HYSizeFit.setPx(1)),
                                        shape: RoundedRectangleBorder(
                                            borderRadius:
                                            BorderRadius.circular(5)),
                                        child: Text(
                                          '交工请求',
                                          style: TextStyle(
                                              color: Colors.black87,
                                              fontSize: HYSizeFit.setPx(12)),
                                        ),
                                        onPressed: () => {}),
                                  ),
                                ],
                              ),
                            ],
                          ),
                          Padding(padding: EdgeInsets.only(left: HYSizeFit.setPx(10))),
                          Column(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                  Global.findUserProcedures.packageProcedures[position]['pdDemand'] != null ?
                                  //"开始时间：" + Global.findUserProcedures.packageProcedures[position]['pdProtime']:
                                  "数量：" + Global.findUserProcedures.packageProcedures[position]['pdDemand'].toString()
                                      : "未设置",
                                  style: TextStyle(
                                    color: Colors.black54,
                                    fontSize: HYSizeFit.setPx(12),
                                  )),
                              Text(
                                  Global.findUserProcedures.packageProcedures[position]['pdProtime'] != null ?
                                  "开始时间：" + formatDate(DateTime.parse(Global.findUserProcedures.packageProcedures[position]['pdProtime']), [yyyy, '-', mm, '-', dd]):
                                  "未设置",
                                  style: TextStyle(
                                    color: Colors.black54,
                                    fontSize: HYSizeFit.setPx(12),
                                  )),
                              Text(
                                  Global.findUserProcedures.packageProcedures[position]['pdDeltime'] != null?
                                  "结束时间：" + formatDate(DateTime.parse(Global.findUserProcedures.packageProcedures[position]['pdDeltime']), [yyyy, '-', mm, '-', dd]):
                                  "未设置",
                                  style: TextStyle(
                                    color: Colors.black54,
                                    fontSize: HYSizeFit.setPx(12),
                                  )),
                              Text(
                                  Global.findUserProcedures.packageProcedures[position]['pdDemand'] != null ?
                                  //"开始时间：" + Global.findUserProcedures.packageProcedures[position]['pdProtime']:
                                  "所需业务：" +
                                      Global.findUserProcedures.packageProcedures[position]['pdDemand'].toString() : "未设置",
                                  style: TextStyle(
                                    color: Colors.black54,
                                    fontSize: HYSizeFit.setPx(12),
                                  )),
                            ],
                          ),
                        ],
                      ),
                    ),
                    Padding(
                      padding: EdgeInsets.only(left: HYSizeFit.setPx(15)),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: <Widget>[
                              Padding(
                                padding: EdgeInsets.only(),
                                child: RichText(
                                    text: TextSpan(
                                        style: TextStyle(
                                          fontSize: HYSizeFit.setPx(17),
                                          color: Colors.black,
                                        ),
                                        children: [
                                          WidgetSpan(
                                              child: Padding(
                                                padding: const EdgeInsets.symmetric(
                                                    horizontal: 2.0),
                                                child: Icon(Icons.person),
                                              )),
                                          TextSpan(text: '    需求方'),
                                        ])),
                              ),
                              Row(
                                children: [
                                  Text(
                                      Global.findUserProcedures
                                          .packageProcedures[position]
                                      ['usrName'],
                                      //textAlign: TextAlign.center,
                                      style: TextStyle(
                                        //color: Colors.grey[700],
                                        fontSize: HYSizeFit.setPx(15),
                                        height: 1.2,
                                      )),
                                  IconButton(
                                      icon: Icon(
                                        Icons.arrow_forward_ios,
                                        color: Colors.grey,
                                      ),
                                      onPressed: () => {}),
                                ],
                              )
                            ],
                          ),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: <Widget>[
                              Padding(
                                padding: EdgeInsets.only(),
                                child: RichText(
                                    text: TextSpan(
                                        style: TextStyle(
                                          fontSize: HYSizeFit.setPx(17),
                                          color: Colors.black,
                                        ),
                                        children: [
                                          WidgetSpan(
                                              child: Padding(
                                                padding: const EdgeInsets.symmetric(
                                                    horizontal: 2.0),
                                                child: Icon(Icons.paste),
                                              )),
                                          TextSpan(text: '    所属订单'),
                                        ])),
                              ),
                              Row(
                                children: [
                                  Text(
                                      Global.findUserProcedures
                                          .packageProcedures[position]
                                      ['pjName'],
                                      //textAlign: TextAlign.center,
                                      style: TextStyle(
                                        //color: Colors.grey[700],
                                        fontSize: HYSizeFit.setPx(15),
                                        height: 1.2,
                                      )),
                                  IconButton(
                                      icon: Icon(
                                        Icons.arrow_forward_ios,
                                        color: Colors.grey,
                                      ),
                                      onPressed: () => {}),
                                ],
                              )
                            ],
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
                Positioned(
                    top: HYSizeFit.setPx(-7),
                    right: 0,
                    child: GestureDetector(
                      child: Container(
                        height: HYSizeFit.setPx(20),
                        width: HYSizeFit.setPx(50),
                        decoration: new BoxDecoration(
                          //border: new Border.all(color: Colors.black12, width: 0.5), // 边色与边宽度
                          color: Colors.black12, // 底色
                          borderRadius:
                          BorderRadius.all(Radius.circular(7.0)), // 也可控件一边圆角大小
                          //borderRadius: new BorderRadius.vertical(top: Radius.elliptical(20, 60)),
                        ),
                        //color: Colors.black12,
                        child: Icon(
                          Icons.linear_scale_rounded,
                          size: HYSizeFit.setPx(30),
                          color: Colors.blueGrey,
                        ),
                      ),
                      onTap: () {
                        final foldingCellState = context
                            .findAncestorStateOfType<SimpleFoldingCellState>();
                        foldingCellState?.toggleFold();
                      },
                    ))
              ],
            ),
          );
        });
  }

  Future<void> _onApplyFinish(BuildContext context, int position)  async {
    var status = await EA(context).completeApplication(Global.findUserProcedures.packageProcedures[position]['usrId'],
                                                        Global.findUserProcedures.packageProcedures[position]['pjId'],
                                                        Global.findUserProcedures.packageProcedures[position]['pdId'],);
    if(status == 200){
      await AplSuccessedCard(context);
    }
    else await UnderAppFailedCard(context);
  }

}

class UpdateProgress extends StatefulWidget {
  UpdateProgress({
    Key key,
    this.pdId,
    this.schedule
  }) : super(key: key);
  final int pdId;
  final String schedule;
  @override
  State<StatefulWidget> createState() {
    return UpdateProgressState(pdId, schedule);
  }
}

class UpdateProgressState extends State<UpdateProgress> {
  double mCurrentValue = 0.0;
  final int pdId;
  final String schedule;
  UpdateProgressState(this.pdId, this.schedule);

  @override
  Widget build(BuildContext context) {
    return Material(
        type: MaterialType.transparency,
        child: Stack(
          alignment: AlignmentDirectional.center,
          children: [
            Container(
              height: HYSizeFit.setPx(190),
              //width: HYSizeFit.setPx(300),
                decoration: ShapeDecoration(
                  color: Colors.white,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.all(
                      Radius.circular(8.0),
                    ),
                  ),
                ),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      Padding(
                          padding: EdgeInsets.only(left: 10,top: HYSizeFit.setPx(15)),
                          child: Text(
                            "进度更新",
                            style: TextStyle(
                                color: Colors.black87,
                                fontSize: HYSizeFit.setPx(20),
                                fontWeight: FontWeight.w500),
                          )),
                    ],
                  ),
                  Padding(padding: EdgeInsets.only(top: HYSizeFit.setPx(20))),
                  SliderTheme(
                    data: SliderTheme.of(context).copyWith(
                      activeTrackColor: Colors.blueGrey,
                      activeTickMarkColor: Colors.white,
                      inactiveTickMarkColor: Colors.white,
                      inactiveTrackColor: Colors.black,
                      valueIndicatorColor: Colors.black45,
                      thumbColor: Colors.black87,
                      overlayColor: Colors.black12,
                    ),
                    child: new Container(
                      margin: const EdgeInsets.all(10.0),
                      child: new Row(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: <Widget>[
                          new Text(
                              '0%',
                            style: TextStyle(
                              fontSize: HYSizeFit.setPx(20),
                            ),
                          ),
                          new Expanded(
                              child: new Slider(
                                onChanged: (double value) {
                                  setState(() {
                                    mCurrentValue = value;
                                  });
                                },
                                divisions: 10, //不想出现刻度和气泡,删除这个属性就可以了，自己实验
                                label: "${mCurrentValue * 100}" + '%',
                                value: mCurrentValue,
                              )),
                          new Text(
                              '100%',
                            style: TextStyle(
                              fontSize: HYSizeFit.setPx(20),

                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: <Widget>[
                      FlatButton.icon(
                        icon: Icon(Icons.close),
                        label: Text("取消"),
                        onPressed: (){
                          Navigator.pop(context);
                        },
                      ),
                      FlatButton.icon(
                        icon: Icon(Icons.done),
                        label: Text("确认"),
                        onPressed: ()async{
                          if( await _onUpdateProgress(pdId, (mCurrentValue*100).toString()) == 200 ){
                            Navigator.pop(context);
                          }
                        },
                      ),
                    ],
                  ),
                ],
              )
            )
          ],
        )
        );
  }
  Future<int> _onUpdateProgress(int pdId, String schedule) async {
    var status = await EA(context).updateProgress(pdId, schedule);
    print(status);
    return status;
  }
}
